"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const SafeTool_1 = __importDefault(require("../../lib/YaoDo/Source/SafeTool"));
const LogTool_1 = __importDefault(require("../LogTool/LogTool"));
const webSocketTool = {
    wsMap: new Map(),
    listenMap: new Map(),
    start: function (wss) {
        let that = this;
        wss.on('connection', (ws) => {
            const uuid = SafeTool_1.default.generateUUID();
            const ipv6 = ws._socket.remoteAddress;
            const ipv4 = ipv6.replace('::ffff:', '');
            if (!that.wsMap.has(uuid)) {
                that.wsMap.set(uuid, { ipv4, ws });
            }
            ws.on('message', (msg) => {
                try {
                    const mesJson = JSON.parse(msg.toString());
                    if ('username' in mesJson) {
                        LogTool_1.default.getLogger().then((logger) => {
                            logger.info('webSocketTool', { message: `客户端连接成功：` + JSON.stringify(mesJson) });
                        });
                        that.wsMap.set(uuid, {
                            ipv4,
                            username: mesJson.username,
                            userType: mesJson.userType,
                            ws
                        });
                        this.sendToAllUser(JSON.stringify({
                            'bid': 'network',
                            'data': this.getAllClient(),
                            'timestamp': new Date().getTime()
                        }));
                    }
                    else {
                        LogTool_1.default.getLogger().then((logger) => {
                            logger.info('webSocketTool', { message: `收到客户端数据：${msg.toString()}}` });
                        });
                    }
                    that.listenMap.forEach((func) => {
                        if (typeof func === 'function') {
                            func(mesJson);
                        }
                    });
                }
                catch (e) {
                    LogTool_1.default.getLogger().then((logger) => {
                        logger.warn('webSocketTool', { message: `WS 错误！${e}` });
                    });
                }
            });
            ws.on('close', () => {
                that.wsMap.delete(uuid);
                this.sendToAllUser(JSON.stringify({
                    'bid': 'network',
                    'data': this.getAllClient(),
                    'timestamp': new Date().getTime()
                }));
            });
        });
    },
    addListen: function (mark, func) {
        this.listenMap.set(mark, func);
    },
    sendToAllUser(msgStr) {
        if (msgStr) {
            this.wsMap.forEach(({ ws }) => {
                if (ws.readyState === 1) {
                    ws.send(msgStr, (err) => {
                        if (err) {
                            LogTool_1.default.getLogger().then((logger) => {
                                logger.warn('webSocketTool', { message: `向客户端发送消息失败，错误信息：${err}` });
                            });
                        }
                    });
                }
                else if (ws.readyState === 2) {
                    ws.close();
                    this.wsMap.delete(ws);
                    LogTool_1.default.getLogger().then((logger) => {
                        logger.warn('webSocketTool', { message: `一个客户端正在关闭，当前在线客户端数量：${this.wsMap.size}` });
                    });
                }
                else if (ws.readyState === 3) {
                    ws.close();
                    this.wsMap.delete(ws);
                    LogTool_1.default.getLogger().then((logger) => {
                        logger.warn('webSocketTool', { message: `一个客户端已经关闭，当前在线客户端数量：${this.wsMap.size}` });
                    });
                }
            });
        }
    },
    sendById(uuid, msgStr) {
        const { ws } = this.wsMap.get(uuid);
        if (ws && msgStr) {
            ws.send(msgStr, (err) => {
                if (err) {
                    LogTool_1.default.getLogger().then((logger) => {
                        logger.warn('webSocketTool', { message: `向客户端发送消息失败，错误信息：${err}` });
                    });
                }
            });
        }
        else {
            LogTool_1.default.getLogger().then((logger) => {
                logger.warn('webSocketTool', { message: `向客户端发送消息失败，错误信息：uuid为空或msgStr为空` });
            });
        }
    },
    getAllClient() {
        const clients = [];
        for (const [key, item] of this.wsMap) {
            const client = { ...item };
            delete client.ws;
            clients.push({ id: key, ...client });
        }
        return clients;
    }
};
exports.default = webSocketTool;
